package cn.idarkboss.org.mybatis.services;

import cn.idarkboss.org.mybatis.entity.TbStudent;
import cn.idarkboss.org.mybatis.mapper.TbStudentMapper;
import cn.idarkboss.org.mybatis.services.common.MybatisService;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MybatisApplicationImpl implements MybatisService {
    @Resource
    private TbStudentMapper tbStudentMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 造数据
     *
     * @param size
     * @return
     */
    @Override
    public List<TbStudent> createData(int size) {
        List<TbStudent> studentList = new ArrayList<>();
        TbStudent student;
        for (int i = 1; i <= size; i++) {
            student = new TbStudent();
            // student.setId(i);
            student.setStudentId("S" + i);
            student.setName("小王" + i);
            student.setAge(18);
            student.setSex(1);
            student.setDept("略略略");
            student.setAddress("黄浦江底别墅" + i + "号");
            studentList.add(student);
        }

        return studentList;
    }

    /**
     * 批量插入
     *
     * @param list
     */
    @Override
    public void InsertBatch(List<TbStudent> list) {
        // 使用批处理
        long start = System.currentTimeMillis();
        try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
            TbStudentMapper studentMapperNew = sqlSession.getMapper(TbStudentMapper.class);
            list.forEach(studentMapperNew::insert);
            sqlSession.commit();
            sqlSession.clearCache();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Foreach插入
     *
     * @param list
     */
    @Override
    public void InsertForeach(List<TbStudent> list) {
        tbStudentMapper.batchInsert(list);
    }

    /**
     * 逐个插入
     *
     * @param list
     */
    @Override
    public void InsertOneByOne(List<TbStudent> list) {
        long start = System.currentTimeMillis();
        list.forEach(student -> tbStudentMapper.insert(student));
    }
}
